package com.eastfair.imaster.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.core.utils.StringUtils;
import com.eastfair.enums.SortTypeEnum;
import com.eastfair.imaster.dao.VisitorUserMapper;
import com.eastfair.imaster.dto.VisitorRegisterDTO;
import com.eastfair.imaster.dto.VisitorRegisterStateDTO;
import com.eastfair.imaster.dto.VisitorUserDTO;
import com.eastfair.imaster.entity.VisitorUser;
import com.eastfair.imaster.service.VisitorUserService;
import com.eastfair.imaster.vo.VisitorUserVO;
import com.eastfair.projectcore.api.ProjectCoreServiceFeign;
import com.eastfair.core.snowflake.DefaultUidGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 业务实现类
 * 观众用户信息表（根据显示需求灌入数据）
 * </p>
 *
 * @author zjn
 * @date 2021-08-25
 */
@Slf4j
@Service
@DS("#thread.tenant")
public class VisitorUserServiceImpl extends SuperServiceImpl<VisitorUserMapper, VisitorUser> implements VisitorUserService {

    @Autowired
    private ProjectCoreServiceFeign projectCoreServiceFeign;

    /**************sharding 分库分表操作 *****************/
    @Override
    public boolean updateByIdOfShard(VisitorUser entity) {
        UpdateWrapper<VisitorUser> updateWrapper = new UpdateWrapper<>();
        //可将指定字段更新为null
        updateWrapper.lambda().eq(VisitorUser::getProjectId, ContextUtil.getProjectId()).eq(VisitorUser::getId, entity.getId());
        entity.setProjectId(null);
        //删除缓存
        return SqlHelper.retBool(this.getBaseMapper().update(entity, updateWrapper));
    }

    @Override
    protected R<Boolean> handlerSave(VisitorUser model) {
        //雪花ID
        model.setId(DefaultUidGenerator.getUidOfProjectId(ContextUtil.getProjectId()));
        model.setProjectId(ContextUtil.getProjectId());
        return R.successDef();
    }

    @Override
    public void saveVisitorUser(VisitorRegisterDTO visitorRegisterDTO, VisitorRegisterStateDTO visitorRegisterStateDTO) {
        // 信息拷贝
        VisitorUser visitorUser = BeanUtil.copyProperties(visitorRegisterDTO, VisitorUser.class);
        BeanUtil.copyProperties(visitorRegisterStateDTO, visitorUser);

        // 更新或保存信息
        QueryWrapper<VisitorUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VisitorUser::getProjectId, visitorUser.getProjectId())
                .eq(VisitorUser::getExhibitionId, ContextUtil.getExhibitionId())
                .eq(VisitorUser::getUserAccountId, visitorRegisterDTO.getUserAccountId());
        VisitorUser oldVisitorUser = getOne(queryWrapper, true);
        if (Objects.isNull(oldVisitorUser)) {
            visitorUser.setId(null);
            save(visitorUser);
        } else {
            visitorUser.setId(oldVisitorUser.getId());
            updateByIdOfShard(visitorUser);
        }
    }

    @Override
    public Page<VisitorUserVO> getVisitorList(PageParams<VisitorUserDTO> visitorUserDTOPageParams) {
        // 转换查询条件
        QueryWrapper<VisitorUser> wrapper = getQueryWrapper(visitorUserDTOPageParams.getModel());
        Page<VisitorUser> visitorUserPage = page(visitorUserDTOPageParams.buildPage(), wrapper);

        // 类型转换并返回
        return ConvertUtil.convertPage(visitorUserPage, VisitorUserVO.class);
    }

    /**
     * 转换查询条件
     *
     * @param visitorUserDTO 观众筛选信息
     * @return 观众用户列表查询条件
     */
    QueryWrapper<VisitorUser> getQueryWrapper(VisitorUserDTO visitorUserDTO) {
        QueryWrapper<VisitorUser> queryWrapper = new QueryWrapper<>();
        // 默认查询条件
        queryWrapper.lambda().eq(VisitorUser::getIsEnabled, BusinessConstant.ENABLE_YES).eq(VisitorUser::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(VisitorUser::getProjectId, ContextUtil.getProjectId());

        // 业务筛选条件
        if (visitorUserDTO == null) {
            return queryWrapper;
        }
        if (!StringUtils.isBlank(visitorUserDTO.getName())) {
            queryWrapper.lambda().like(VisitorUser::getName, visitorUserDTO.getName());
        }

        // TODO 待统一 排序条件
        if (visitorUserDTO.getOrderBy() != null) {
            if (SortTypeEnum.DESC.eq(visitorUserDTO.getSortType())) {
                queryWrapper.orderByDesc(visitorUserDTO.getOrderBy());
            } else {
                queryWrapper.orderByAsc(visitorUserDTO.getOrderBy());
            }
        }
        return queryWrapper;
    }

}
